<?php

namespace app\admin\controller\used;

use app\common\controller\Backend;
use app\common\model\ServiceImage;
use app\common\model\UsedCar;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Car extends Backend
{

    /**
     * Car模型对象
     * @var \app\admin\model\used\Car
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\UsedCar();

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                    ->with(['member','shop','models','series','brand'])
                    ->where($where)
                    ->where('used_car.is_del',0)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as &$row) {
                $dif =  getMonthNum($row['car_age'],time());
                $str = '';
                if ($dif[1] >0){
                    $str = $dif[1].'年';
                }
                if ($dif[2] >0){
                    $str = $str.$dif[2].'月';
                }

                $row['car_age'] = $str;
                $row['price'] = sprintf("%01.2f", $row['price']);
                $row['car_name'] = $row['brand']['name'].$row['series']['name'].$row['models']['name'].$row['models']['year'];
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $info = UsedCar::get($ids,['models','series','brand','cartype','level','discharge','gearbox','swept'])->toArray();
        $info['car_type_name'] = $info['cartype']['name'] ?? '';
        $info['gearbox'] = $info['gearbox']['name'] ?? '';
        $info['level'] = $info['level']['name'] ?? '';
        $info['swept_volume'] = $info['swept']['name'] ?? '';
        $info['discharge'] = $info['discharge']['name'] ?? '';
        $info['car_type_name'] = $info['cartype']['name'] ?? '';
        $info['mileage'] = $info['mileage'].'万公里';
        $info['price'] = sprintf("%01.2f", $info['price']).'万元';
        $info['down_payment'] = empty($info['down_payment']) ? '' : sprintf("%01.2f", $info['down_payment']);
        $dif =  getMonthNum($info['car_age'],time());
        $str = '';
        if ($dif[1] >0){
            $str = $dif[1].'年';
        }
        if ($dif[2] >0){
            $str = $str.$dif[2].'月';
        }
        $info['car_name'] = $info['brand']['name'].$info['series']['name'].$info['models']['name'].$info['models']['year'];
        $info['createtime'] = date('Y.m.d',$info['createtime']);
        $info['car_age'] = $str;
        $info['images'] = ServiceImage::where(['main_id'=>$info['id'],'service_type'=>1])->select()->column('image');
        $info['images'] = implode(',',$info['images']);
        $this->view->assign("row", $info);
        return $this->view->fetch();
    }


    /**
     * 审核通过
     */
    public function pass($ids = NULL)
    {
        try{
            if (empty($ids)){
                throw new Exception('参数ID缺失');
            }
            $info = UsedCar::get($ids);
            if (empty($info)){
                throw new Exception('该条记录信息不存在');
            }
            $flag = UsedCar::update(['status'=>1,'show'=>1],['id'=>$ids]);
            if ($flag == false){
                throw new Exception('更新失败');
            }
            $this->success();
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }

    /**
     * 下架
     */
    public function down($ids = NULL)
    {
        try{
            if (empty($ids)){
                throw new Exception('参数ID缺失');
            }
            $info = UsedCar::get($ids);
            if (empty($info)){
                throw new Exception('该条记录信息不存在');
            }
            $flag = UsedCar::update(['status'=>2,'show'=>2],['id'=>$ids]);
            if ($flag == false){
                throw new Exception('更新失败');
            }
            $this->success();
        }catch (Exception $e){
            $this->error($e->getMessage());
        }
    }


}
